//
//  JFTRequest.m
//  JftMergeSDK
//
//  Created by zhl on 2017/2/10.
//  Copyright © 2017年 HLZ. All rights reserved.
//

#import "JZMRequest.h"
#import <SystemConfiguration/SCNetworkReachability.h>
#import <UIKit/UIKit.h>
#import "JZMExceptionModel.h"
#import "JZMDES.h"
#import "JZMConfigureHeader.h"
#import <netinet/in.h>
#import <CoreTelephony/CTTelephonyNetworkInfo.h>
#import <CoreTelephony/CTCarrier.h>
#import "JZMFileManager.h"
@interface JZMRequest()
@property (nonatomic,strong)NSURLSession*session;
@end
@implementation JZMRequest
+(instancetype)requestManager{
    static JZMRequest *shareRequest =nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        shareRequest =[self new];
    });
    return shareRequest;
}

-(NSURLSession *)session{
    if (!_session) {
        _session =[NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    }
    return _session;
}

-(BOOL)ConnectedToNetwork
{
    // Create zero addy
    struct sockaddr_in zeroAddress;
    bzero(&zeroAddress, sizeof(zeroAddress));
    zeroAddress.sin_len = sizeof(zeroAddress);
    zeroAddress.sin_family = AF_INET;
    // Recover reachability flags
    SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
    SCNetworkReachabilityFlags flags;
    BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
    CFRelease(defaultRouteReachability);
    if (!didRetrieveFlags)
    {
        printf("Error. Could not recover network reachability flags\n");
        return NO;
    }
    BOOL isReachable = ((flags & kSCNetworkFlagsReachable) != 0);
    BOOL needsConnection = ((flags & kSCNetworkFlagsConnectionRequired) != 0);
    return (isReachable && !needsConnection) ? YES : NO;
}

- (NSString *)getOperatorName{
    //获取本机运营商名称
    CTTelephonyNetworkInfo *info = [[CTTelephonyNetworkInfo alloc] init];
    CTCarrier *carrier = [info subscriberCellularProvider];
    //当前手机所属运营商名称
    NSString *mobile;
    //先判断有没有SIM卡，如果没有则不获取本机运营商
    if (!carrier.isoCountryCode) {
        mobile = @"无运营商";
    }else{
        mobile = [carrier carrierName];
    }
    return mobile;
}

//获得外网IP
-(void)deviceWANIPAdress:(void(^)(NSString*returnCity)) ipBlock{
    NSURL *ipURL = [NSURL URLWithString:@"http://pv.sohu.com/cityjson?ie=utf-8"];
    NSURLSessionDataTask *task =[self.session dataTaskWithURL:ipURL completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSString *ipnum = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        NSMutableString*ipmutable =[[NSMutableString alloc]initWithString:ipnum];
        NSError *err =nil;
            if ([ipmutable hasPrefix:@"var returnCitySN = "]) {
                //对字符串进行处理，然后进行json解析
                //删除字符串多余字符串
                NSRange range = NSMakeRange(0, 19);
                [ipmutable deleteCharactersInRange:range];
                NSString * nowIp =[ipmutable substringToIndex:ipmutable.length-1];
                //将字符串转换成二进制进行Json解析
                NSData * data = [nowIp dataUsingEncoding:NSUTF8StringEncoding];
                NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&err];
                if (dict||[dict[@"cname"] isKindOfClass:[NSString class]]) {
                    ipBlock(dict[@"cname"]);
                }
            }
    }];
    [task resume];
}
-(NSString *)getNetWorkStates{
    UIApplication *app = [UIApplication sharedApplication];
//    NSArray *children = [[[app valueForKeyPath:@"statusBar"] valueForKeyPath:@"foregroundView"] subviews];
    NSArray *children;
    if ([[app valueForKeyPath:@"_statusBar"] isKindOfClass:NSClassFromString(@"UIStatusBar_Modern")]) {
        children = [[[[app valueForKeyPath:@"_statusBar"] valueForKeyPath:@"_statusBar"] valueForKeyPath:@"foregroundView"] subviews];
    } else {
        children = [[[app valueForKeyPath:@"_statusBar"] valueForKeyPath:@"foregroundView"] subviews];
    }
    NSString *state = [[NSString alloc]init];
    int netType = 0;
    //获取到网络返回码
    for (id child in children) {
        if ([child isKindOfClass:NSClassFromString(@"UIStatusBarDataNetworkItemView")]) {
            netType = [[child valueForKeyPath:@"dataNetworkType"]intValue];
            switch (netType) {
                case 0:
                    state = @"无网络";
                    break;
                case 1:
                    state = @"2G";
                    break;
                case 2:
                    state = @"3G";
                    break;
                case 3:
                    state = @"4G";
                    break;
                case 5:
                    state = @"WIFI";
                    break;
                default:
                    break;
            }
        }
    }
    return [[self getOperatorName] stringByAppendingString:state];
}
- (void)getDataWithUrl:(NSURL *)url WithParameters:(NSDictionary *)parDictionary Sucessfil:(void (^)(id))Sucessful failure:(void (^)(id failerObjc))failure error:(void (^)(NSError * err))errorBlock{
    if (![self ConnectedToNetwork]) {
        failure (@"没有网络连接");
        return;
    }
    NSMutableURLRequest *mutableUrlRequest =[NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20];

    NSURLSessionDataTask *task =[self.session dataTaskWithRequest:mutableUrlRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error) {
            errorBlock(error);
            return ;
        }
        NSHTTPURLResponse *ponse =(NSHTTPURLResponse*)response;
        if (ponse.statusCode!=200) {
            NSString *str = [NSString stringWithFormat:@"%ld",(long)ponse.statusCode];
        failure(str);
            return;
        }
        NSError*jsonError=nil;
        id returnData =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&jsonError];
        if (jsonError) {
            errorBlock(jsonError);
            return;
        }
        if (returnData) {
            Sucessful (returnData);
        }
    }];
    [task resume];
}

- (void)postDataWithUrl:(NSURL *)url WithParameters:(NSString*)parDictionary Sucessfil:(void (^)(id))Sucessful failure:(void (^)(id failerObjc))failure error:(void (^)(NSError * err))errorBlock{
    if (![self ConnectedToNetwork]) {
        failure (@"没有网络连接");
        return;
    }
    NSMutableURLRequest *mutableUrlRequest =[NSMutableURLRequest requestWithURL:url cachePolicy:1 timeoutInterval:40];
    NSData *jsonData =[parDictionary dataUsingEncoding:NSUTF8StringEncoding];
    mutableUrlRequest.HTTPMethod =@"POST";
    mutableUrlRequest.HTTPBody=jsonData;
    NSURLSessionDataTask *task =[self.session dataTaskWithRequest:mutableUrlRequest  completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error) {
            errorBlock(error);
            return ;
        }
        NSHTTPURLResponse *ponse =(NSHTTPURLResponse*)response;
        if (ponse.statusCode!=200) {
            errorBlock(error);
            return;
        }
        NSError*jsonError;
        id returnData =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&jsonError];
        Sucessful (returnData);
    }];
    [task resume];
}

- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * __nullable credential))completionHandler{
    completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
}
- (void)submitInfo:(JZMExceptionModel*)model andUrl:(NSString *)postUrl{
    if (model) {
        [JZMFileManager addModel:model];
    }
    NSMutableDictionary *endic =[JZMFileManager readAllData];
    if (!endic) {
        return;
    }
//    NSLog(@"%@",endic);
    NSData *mmdata =[NSJSONSerialization dataWithJSONObject:endic options:NSJSONWritingPrettyPrinted error:nil];
    NSString *enStr=[[NSString alloc]initWithData:mmdata encoding:NSUTF8StringEncoding];
    NSString*miwen =   [JZMDES encryptWithContent:enStr type:0 key:[[JZMDES md532BitUpper:[JZMDESKEY stringByAppendingString:@"abcdefg"]] substringToIndex:8]];
    NSString *specialStr =[JZMDES replaceNormalCharacter:miwen];
    NSString *encodeURL =[JZMDES encodeToPercentEscapeString:specialStr];
    NSString *myUrlString =[NSString stringWithFormat:@"%@/sdk/UploadTheLog",postUrl];
    NSURL *url=[NSURL URLWithString:myUrlString];
//    NSLog(@"%@",encodeURL);
    [self postDataWithUrl:url WithParameters:[NSString stringWithFormat:@"nonce=abcdefg&info=%@",encodeURL] Sucessfil:^(id returnData) {
//        NSLog(@"%@",returnData);
        if ([returnData isKindOfClass:[NSDictionary class]]) {
            NSDictionary *returnDic =returnData;
            if ([returnDic[@"flag"] boolValue]) {
                NSString *ddstr=[NSString stringWithFormat:@"%@",[JZMDES replaceSpecialCharacter:returnDic[@"msg"]]];
                NSString *keyyStr=[[JZMDES md532BitUpper:[JZMDESKEY stringByAppendingString:[returnDic objectForKey:@"nonce"]]] substringToIndex:8];
                [JZMDES encryptWithContent:ddstr type:1 key:keyyStr];
                NSString *jsonStr =[JZMDES encryptWithContent:ddstr type:1 key:keyyStr];
                if ([[NSJSONSerialization JSONObjectWithData:[jsonStr dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableLeaves error:nil] isKindOfClass:[NSDictionary class]]) {
                    NSDictionary *jsonDic =[NSJSONSerialization JSONObjectWithData:[jsonStr dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableLeaves error:nil];
                    if ([jsonDic[@"uploadfew"] boolValue]) {
                            [JZMFileManager deleteAll];
                    }
                }
            }
        }
    } failure:^(id failerObjc) {
    } error:^(NSError *err) {
    }];
}
@end
